using System;
using Microsoft.Maui.Controls;

namespace planning_lite
{
    public partial class TaskEditPage : ContentPage
    {
        public TaskItem NewTask { get; private set; } = new TaskItem
        {
            Title = "新任务",
            Description = "待添加描述",
            DueDate = DateTime.Now.AddDays(7),
            CreatedDate = DateTime.Now,
            LastCheckedDate = DateTime.Now.AddDays(-1),
            CheckNeeded = false
        };

        public TaskEditPage()
        {
            InitializeComponent();
            BindingContext = MainPage.currFocusedTask ?? NewTask;
            TaskNameEntry.Text = MainPage.currFocusedTask?.Title ?? NewTask.Title;
            TaskDescriptionEditor.Text = MainPage.currFocusedTask?.Description ?? NewTask.Description;
            PrioritySlider.Value = MainPage.currFocusedTask?.Priority ?? NewTask.Priority;
            TaskDueDatePicker.Date = MainPage.currFocusedTask?.DueDate is null ? DateTime.Now.AddDays(1) : MainPage.currFocusedTask.DueDate.Value;
            CheckNeededSwitch.IsToggled = MainPage.currFocusedTask?.CheckNeeded ?? false;
        }

        private async void OnCancelClicked(object sender, EventArgs e)
        {
            try
            {
                MainPage.OnTasksUpdate?.Invoke();
                await Navigation.PopAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error navigating back: {ex.Message}");
                await DisplayAlert("错误", "无法返回上一页，请稍后再试。", "确定");
            }
        }

        private async void OnSaveClicked(object sender, EventArgs e)
        {
            string taskName = TaskNameEntry.Text;

            if (string.IsNullOrWhiteSpace(taskName))
            {
                await DisplayAlert("提示", "任务名称不能为空", "确定");
                return;
            }
            if (MainPage.currFocusedTask is not null)
            {
                MainPage.currFocusedTask.Title = taskName;
                MainPage.currFocusedTask.Description = TaskDescriptionEditor.Text ?? "";
                MainPage.currFocusedTask.DueDate = TaskDueDatePicker.Date;
                MainPage.currFocusedTask.Priority = (int)PrioritySlider.Value;
                MainPage.currFocusedTask.IsCompleted = false;
                MainPage.currFocusedTask.CreatedDate = DateTime.Now;
                MainPage.currFocusedTask.LastCheckedDate = DateTime.Now.AddDays(-1);
                MainPage.currFocusedTask.CheckNeeded = CheckNeededSwitch.IsToggled;
            }

            MainPage.OnTasksUpdate?.Invoke();

            await Navigation.PopAsync();
        }
    }
}